//
//  YTDriverAuthLicenseViewModel.m
//  YiTuDriverClient
//
//  Created by 石少庸 on 2017/5/12.
//  Copyright © 2017年 Yitu. All rights reserved.
//

#import "YTDriverAuthLicenseViewModel.h"
#import "YTUserProfileServices.h"

@interface YTDriverAuthLicenseViewModel ()

@property (copy, readwrite, nonatomic) NSString *licenseNum;
@property (copy, readwrite, nonatomic) NSString *startDate;
@property (copy, readwrite, nonatomic) NSString *endDate;
@property (strong, readwrite, nonatomic) UIImage *faceImage;

@property (strong, readwrite, nonatomic) RACCommand *submitCommand;

@end

@implementation YTDriverAuthLicenseViewModel

- (void)initialize {
    RACSignal *licenseSignal = [RACObserve(self, licenseNum) map:^id(NSString *value) {
        return @(value.length > 1);
    }];
    
    id (^dateValidate)(NSString *date) = ^id (NSString *date) {
        return @(date.length > 8);
    };
    
    RACSignal *startSignal = [RACObserve(self, startDate) map:dateValidate];
    RACSignal *endSignal = [RACObserve(self, endDate) map:dateValidate];
    RACSignal *imageSignal = [RACObserve(self, faceImage) map:^id(UIImage *value) {
        return @(value != nil);
    }];
    
    RACSignal *enabledSignal = [RACSignal combineLatest:@[licenseSignal, startSignal, endSignal, imageSignal]
                                                 reduce:^id(NSNumber *license, NSNumber *start, NSNumber *end, NSNumber *image) {
        return @(license.boolValue && start.boolValue && end.boolValue && image.boolValue);
    }];
    @weakify(self);
    _submitCommand = [[RACCommand alloc] initWithEnabled:enabledSignal signalBlock:^RACSignal *(id input) {
        @strongify(self);
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[@"licenseId"] = self.licenseNum;
        dict[@"expireTime"] = self.endDate;
        dict[@"getTime"] = self.startDate;
        NSString *faceString = [UIImage yt_imageToString:[[UIImage alloc] yt_imageWithImageSimple:self.faceImage scaledToSize:CGSizeMake(600, 300)]];
        dict[@"licenseImage_new"] = faceString;
        return [YTUserProfileServices driverAuthStep2WithData:dict];
    }];
}

@end
